<?php

class MenuBuilderController extends Controller
{
	public $layout='/layouts/column1';
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','ajaxPrice','preview'),
				'users'=>array('@'),


		),
		array('deny','users'=>array('*')),
		);
	}
	/*
	 public function actions()
	 {
		// return external action classes, e.g.:
		return array(
		'action1'=>'path.to.ActionClass',
		'action2'=>array(
		'class'=>'path.to.AnotherActionClass',
		'propertyName'=>'propertyValue',
		),
		);
		}
		*/
	public function actionAjaxPrice()
	{
		$coffee_shopId=$_GET['coffee_shopId'];
		$coffee_product=$_GET['coffee_product'];
		$coffee_size=$_GET['coffee_size'];
		$coffee_milk=$_GET['coffee_milk'];
		$product=CoffeeProduct::model()->findByAttributes(array(
		'shopId'=>$coffee_shopId,
		'coffeeType'=>$coffee_product,
		'size'=>$coffee_size,
		'milk' =>$coffee_milk,	
		));
		if($product){
			if(is_array($product)){
				$product=$product[0];
			}
			echo CJSON::encode(array('id'=>$product->id,'price'=>$product->price));
		}else{
			echo '{}';
		}
	}
	public function actionIndex()
	{
		$userData=User::model()->findbyPk(Yii::app()->user->id);
		if(empty($userData->email)||empty($userData->mobile)){
			$this->render('../default/profileIncomplete');
			return;
		}


		if(isset($_POST['action'])&&isset($_POST['CoffeeOrder'])){
			$userid=Yii::app()->user->getId();
			$model=CoffeeOrder::model()->findByAttributes(array(
				'lineId'=>$_POST['CoffeeOrder']['lineId'],
				'userId'=>$userid
			));
			if($_POST['action']=='Save')
			{
				if(!$model){
					$model=new CoffeeOrder();
					$model->userId=$userid;
				}

				$model->attributes=$_POST['CoffeeOrder'];
				if($model->validate())
				{
					$model->save();
					$this->processSave($model);
					$url=$this->createUrl('payment/index');
					
					Yii::app()->clientScript->registerScript("jumpOrderRedirect",'setTimeout("window.location = \''.$url.'\'",2000)');
					Yii::app()->user->setFlash('jo_menuBuilder','Order Saved, now redirecting to Payment page in 2 seconds....');
				}
			}else if ($_POST['action']=='Clear'){
				if($model){
					$model->delete();
					Yii::app()->user->setFlash('jo_menuBuilder','Order Cleared');
				}
			}
		}



		$orderLines=$this->getOrderLines(false);
		$availableCoffeeShops=array('0'=>'');
		$dbPos=Pos::model()->with('shop')->together()->findAll();
		foreach ($dbPos as $pos){
			$dbShop=$pos->shop;
			$availableCoffeeShops[$dbShop->id]=$dbShop->name.' - '.$dbShop->suburb.' '.$dbShop->state;
		}

		$this->render('index',array('orderLines'=>$orderLines,'availableCoffeeShops'=>$availableCoffeeShops));
	}

	private function getOrderLines($skipEmpty=true){
		$orderLines=array();
		$maxLine=1;
		for($i=1;$i<=$maxLine;$i++){
			
			$orderLine=CoffeeOrder::model()->findByAttributes(array('userId'=>Yii::app()->user->getId(),'lineId'=>$i));
			if( empty($orderLine) && $skipEmpty){
				continue;
			}
			$orderLines[$i]=$orderLine;
			if(!$orderLines[$i]){
				$orderLines[$i]=new CoffeeOrder('menuBuilder');
				$orderLines[$i]->lineId=$i;
			}
		}
		return $orderLines;
	}

	public function actionPreview(){
		$orderLines=$this->getOrderLines();
		$this->render('preview',array('orderLines'=>$orderLines));
	}

	private function processSave($order){
		$adminMail='msefton@seftonconsulting.com.au';
		$mailer=Yii::app()->mailer;
		$mailer->FromName="Jump Order";
		$mailer->From=$adminMail;
		$mailer->Sender=$adminMail;
		$mailer->AddAddress($adminMail);
		
		$userData=User::model()->findbyPk(Yii::app()->user->id);
		
		$orderLines=$this->getOrderLines();
		$body='<p>User:  '.$userData->email.' '.$userData->profile->firstname.' '.$userData->profile->lastname.' Mobile:'.$userData->mobile.'</p>';
		$body.=$this->renderPartial('preview',array('orderLines'=>$orderLines),true);
		$mailer->Subject = "User has updated order";
		$mailer->Body = $body;
		$mailer->Send();
	}
}